<template>
  <el-card>
    <div slot="header">
      <h3>批量新增进价信息-多计量</h3>
    </div>
    <div>
      <el-row type="flex" style="padding-bottom: 10px">
        <supply @getName="handleGetSupplier"></supply>
        <span style="margin-left: 30px; min-width: 180px"
          >供应商主营品类：{{
            supplyInfo.supMainCategoryName || supplyInfo.supMainCategoryId
          }}</span
        >
        <span style="margin-left: 30px; min-width: 180px"
          >供应商管理区域：{{ supplyInfo.supManagerHrAreaName }}</span
        >
        <span style="margin-left: 30px; min-width: 180px"
          >运费承担方：{{ supplyInfo.freightPayer }}</span
        >
      </el-row>
      <el-row type="flex">
        <el-row type="flex" align="middle">
          <span style="min-width: 100px">选择销售城市：</span>
          <el-button type="text" size="large" @click="handleChooseSaleCity"
            >选择销售城市</el-button
          >
        </el-row>
        <el-row type="flex" align="middle" style="margin-left: 30px">
          <span style="min-width: 70px">已选城市：</span>
          <tool-tip :textContent="saleCity.labels" />
        </el-row>
      </el-row>
      <el-row type="flex" class="item_wrap" align="middle">
        <div>供货价格方式：</div>
        <el-radio-group
          v-model="supplyPriceType"
          @change="handleSwitchPurchaseStatus"
        >
          <el-radio label="1">统一进价</el-radio>
          <el-radio label="2">区域进价</el-radio>
        </el-radio-group>
      </el-row>
      <el-row type="flex" justify="space-between" class="item_wrap">
        <el-row type="flex" align="middle">
          <div>设置参照城市关系：</div>
          <el-button type="primary" @click="handleSetReferCityRelation"
            >设置</el-button
          >
        </el-row>
        <el-row type="flex" justify="end">
          <el-button
            v-if="showBtn('关联商品')"
            type="text"
            size="large"
            @click="handleAssociatedGoods"
            >关联商品</el-button
          >
          <el-button
            v-if="showExportOrSubmitBtn"
            type="text"
            size="large"
            :loading="loading.export"
            @click="handleExportData"
            >模板导出</el-button
          >
          <a
            ><Upload
              class="action_bar_upload"
              :show-upload-list="false"
              :format="['xlsx', 'xls', 'csv']"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-format-error="handleUploadFormatError"
              :before-upload="handleBeforeUpload"
              :data="uploadData"
              :action="`${uploadBaseURL}sysback/supplyareaprice/importTemplateForCreateSteel`"
              ><el-button type="text" size="large">模板导入</el-button></Upload
            ></a
          >
          <el-button
            v-if="showExportOrSubmitBtn"
            type="text"
            size="large"
            :loading="loading.submit"
            @click="handleSubmitPurchaseData"
            >提交</el-button
          >
        </el-row>
      </el-row>
      <!-- 统一进价表格 -->
      <el-row v-if="supplyPriceType == '1'" class="item_wrap">
        <h4>供货价格相关信息如下:</h4>
        <div>
          <skus-table
            :loading="loading.table"
            :data-source="purchaseTable.unifiedData"
            :columns="purchaseTable.unifiedColumns"
            @handleRowSpecialChange="handleRowSpecialChange"
          />
        </div>
      </el-row>
      <!-- 区域进价表格 -->
      <el-row v-if="supplyPriceType == '2'" class="item_wrap">
        <h4>供货价格相关信息如下:</h4>
        <div>
          <skus-table
            :loading="loading.table"
            :data-source="purchaseTable.areaData"
            :columns="purchaseTable.areaColumns"
            @handleRowSpecialChange="handleRowSpecialChange"
          />
        </div>
      </el-row>
    </div>
    <!-- 选择销售城市 -->
    <sale-city-dialog
      ref="saleCity"
      :dialogVisible="saleCity.visible"
      :saleCityList="saleCity.list"
      :hasSelectCityList="saleCity.selected"
      @set-sale-city="handleSetSaleCity"
      @select-area-confirm="handleConfirmSaleCity"
    />
    <!-- 设置参照城市弹框 -->
    <set-reference-city
      :visible.sync="referenceCity.visible"
      :supplierCode="supplyInfo.supplierCode"
      :showReferenceCityColumns="referenceCity.columns"
      :templateTableData="templateCityData"
      :getReferenceCityListAction="getReferenceCityListAction"
      :getSubmitNoAction="getSubmitNoAction"
      @getSetCityData="handleGetSetData"
    />
    <!-- 关联商品-SKU维度弹框 -->
    <associated-goods-modal
      ref="link"
      :columns="associatedGoods.columns"
      :requestApi="associatedGoods.requestApi"
      :requestParams="associatedGoods.requestParams"
      :distinctParams="associatedGoods.distinctParams"
      @submitAction="getAssociatedGoodsAction"
      :pageSizeOpts="[10, 50, 100, 500, 1000]"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters, mapMutations } from 'vuex';
/* components */
import Supply from '@/components/commodity/getSupply.vue';
import SaleCityDialog from '@/components/commodity/selectSaleCityDialog';
import AssociatedGoodsModal from '@/components/common/dialog/associatedGoods/associatedGoodsDialog';
import ToolTip from '@/components/common/toolTip';
import SkusTable from '@/components/skusTable';
import SetReferenceCity from '@/components/common/dialog/setReferenceCity';
/* mixins */
import skuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/skuDimension';
/* constants */
import { requiredParamsOther } from '@/components/common/dialog/associatedGoods/constants/skuDimension';
import { ADD_ENTER_PRICE_INFO_AMOUNT } from '@/constants/exportAmountLimit';
import {
  multipleUnifiedPurchaseColumns,
  multipleAreaPurchaseColumns
} from '@/pages/commodity/modules/constants/purchaseModule/addBatchPurchase'
/* utils */
import { generateUuid } from '@/utils/bizUtils';
import { handleSpecialPriceChangeForMultipleAdd, hasEmptyPriceForMultiple } from '@/utils/price';

export default {
  mixins: [skuDimensionMixins],
  components: {
    Supply,
    SaleCityDialog,
    AssociatedGoodsModal,
    ToolTip,
    SkusTable,
    SetReferenceCity
  },
  data () {
    return {
      supplyPriceType: '1', // 统一进价还是区域进价的状态值，1为统一进价，2为区域进价
      submitNo: '', // 提交表格数据时接口所需编码
      templateCityData: [], // 参照城市表格数据
      showTitle: false, // 是否显示自定义tooltip
      defaultReferenceCity: { // 统一进价设置参照城市的默认参照城市对象
        templateCityUuid: '',
        templateCityName: ''
      },
      /* loading */
      loading: {
        table: false, // 表格loading
        submit: false, // 提交按钮loading
        export: false // 导出按钮loading
      },
      /* 供应商数据参数 */
      supplyInfo: {
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        supMainCategoryId: '', // 供应商主营品类id
        supMainCategoryName: '', // 供应商主营品类name
        supManagerHrAreaName: '', // 供应商管理区域
        freightPayer: '' // 运费承担方
      },
      // 发票类型，税率信息
      taxRateInvoiceInfo: {
        taxRate: '',
        invoiceType: '',
        invoiceTypeName: ''
      },
      /* 表格数据参数 */
      purchaseTable: {
        unifiedData: [], // 统一定价表格数据
        areaData: [], // 区域进价表格数据
        initData: [], // 初始进价表格数据(真实关联弹框所带出的表格数据)，用于设置参照城市后的组装
        unifiedColumns: multipleUnifiedPurchaseColumns, // 统一进价表格columns
        areaColumns: multipleAreaPurchaseColumns, // 区域进价表格columns
      },
      /* 销售城市弹框参数 */
      saleCity: {
        visible: false,
        list: [], // 销售城市列表
        selected: [], // 已选择的销售城市集合
        codes: '', // 已选择的销售城市code集合字符串
        labels: '', // 已选择的销售城市label集合字符串
        chooseAll: ''
      },
      /* 参照城市弹框组件参数 */
      referenceCity: {
        visible: false,
        columns: [
          {
            title: '销售城市',
            key: 'saleCityName',
            minWidth: 150,
            align: 'center'
          },
          { title: '区域', key: 'saleAreaName', minWidth: 150, align: 'center' },
          {
            title: '参照城市',
            key: 'templateCityName',
            minWidth: 150,
            align: 'center'
          },
          {
            title: '进价比例',
            key: 'buyPriceRatio',
            minWidth: 150,
            align: 'center'
          },
          {
            title: '成本价比例',
            key: 'costPriceRatio',
            minWidth: 150,
            align: 'center'
          }
        ]
      },
      /* 关联商品弹框组件参数 */
      associatedGoods: {
        requestApi: {
          url: [],
          type: 'post'
        },
        requestParams: [
          ...requiredParamsOther.requestParams,
          {
            name: 'isSaleMultiUnit_s',
            value: '1'
          }
        ],
        distinctParams: requiredParamsOther.distinctParams,
        columns: [
          { type: 'selection', width: 60, align: 'center' },
          { title: '商品名称', key: 'productName', minWidth: 120 },
          { title: 'SPU编码', key: 'spuNo', minWidth: 120 },
          { title: '商品分类', key: 'categoryPath', minWidth: 120 },
          { title: 'SKU编码', key: 'skuNo', minWidth: 120 },
          { title: '规格参数', key: 'specDetailStr', minWidth: 120 },
          { title: '品牌', key: 'brandName', minWidth: 120 },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            fixed: 'right',
            minWidth: 100
          }
        ],
      },
      /* 模板导入参数 */
      uploadData: {
        supplyUuid: '',
        purchasePriceType: '1'
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    /* 导出按钮和提交按钮的显隐条件 */
    showExportOrSubmitBtn () {
      let flag = false;
      if (
        this.supplyPriceType === '1' &&
        this.purchaseTable.unifiedData.length > 0
      ) {
        flag = true;
      }
      if (
        this.supplyPriceType === '2' &&
        this.purchaseTable.areaData.length > 0
      ) {
        flag = true;
      }
      return flag;
    }
  },
  methods: {
    ...mapMutations('commonComps/setReferenceCity', [
      'SET_TABLE_DATA',
      'SET_REFERENCE_CITIES',
      'SET_PURCHASE_PRICETYPE',
      'DESTORY_STATE'
    ]),
    /* 选择供应商 */
    handleGetSupplier (data) {
      let {
        supplierCode,
        supplierName,
        supMainCategoryId,
        supMainCategoryName,
        supManagerHrAreaName,
        freightPayer,
        taxRate,
        invoiceType,
        invoiceTypeName
      } = data;
      // 初始化
      if (this.supplyInfo.supplierCode !== supplierCode) {
        this.purchaseTable.initData = [];
        this.purchaseTable.areaData = [];
        this.purchaseTable.unifiedData = [];
        this.saleCityClearFn(); // 清空销售城市
        this.CLEAR_GOODS(); // 清除关联商品ID
        this.resetReferenceCityDataFn();
      }
      this.supplyInfo = {
        supplierCode,
        supplierName,
        supMainCategoryId,
        supMainCategoryName,
        supManagerHrAreaName,
        freightPayer
      };
      this.uploadData.supplyUuid = supplierCode;
      this.taxRateInvoiceInfo = {
        taxRate,
        invoiceType,
        invoiceTypeName
      }
    },
    /* 选择销售城市 */
    handleChooseSaleCity () {
      if (this.saleCity.list.length === 0) {
        let data = {};
        ApiRequest(
          '/sysback/supplyinfofromsrcm/getAllAreaFromScrm',
          'post',
          data,
          true
        ).then((res) => {
          if (res.retStatus == '1') {
            this.saleCity.visible = true;
            this.saleCity.list = res.retData;
          }
        });
        return false;
      }
      this.saleCity.visible = true;
    },
    /* 勾选销售城市 */
    handleSetSaleCity (params) {
      let { data, chooseType } = params;
      this.saleCity.selected = data;
      this.saleCity.chooseAll = chooseType;
    },
    /* 确定选择的销售城市 */
    handleConfirmSaleCity () {
      if (this.saleCity.selected.length === 0) {
        this.saleCity.visible = false;
        return this.$message.warning('请选择销售区域');
      }
      let codeList = [];
      let labelList = [];
      this.saleCity.selected.forEach((item) => {
        codeList.push(item.areaCode);
        labelList.push(item.areaName);
      });
      this.saleCity.codes = codeList.join(',');
      this.saleCity.labels = labelList.join(',');
      this.saleCity.visible = false;
      /* 确定销售城市弹框时要清空参照城市关系，并且表格数据初始化 */
      this.resetReferenceCityDataFn();
      this.switchPurchaseTypeInitTableDataFn(this.purchaseTable.initData);
    },
    /* 销售城市清空 */
    saleCityClearFn () {
      this.saleCity = {
        visible: false,
        list: [], // 销售城市列表
        selected: [], // 已选择的销售城市集合
        codes: '', // 已选择的销售城市code集合字符串
        labels: '', // 已选择的销售城市label集合字符串
        chooseAll: ''
      }
    },
    /* 切换供货价格方式，1为统一进价，2为区域进价 */
    handleSwitchPurchaseStatus () {
      this.uploadData.purchasePriceType = this.supplyPriceType; // 改变进价类型
      this.resetReferenceCityDataFn();
      this.getAssociatedGoodsAction();
    },
    /* 设置参照城市 */
    handleSetReferCityRelation () {
      if (!this.supplyInfo.supplierCode) {
        return this.$message.warning('请先选择供应商');
      }
      if (!this.saleCity.codes) {
        return this.$message.warning('请选择销售城市');
      }
      if (
        this.supplyPriceType === '1' &&
        this.purchaseTable.unifiedData.length === 0
      ) {
        return this.$message.warning('请先关联商品');
      }
      if (
        this.supplyPriceType === '2' &&
        this.purchaseTable.areaData.length === 0
      ) {
        return this.$message.warning('请先关联商品');
      }
      let passedFlag = this.judgeTableNumLimitFn();
      if (!passedFlag) { return false }
      this.referenceCity.visible = true;
    },
    /* 获取当前销售区域的参照城市列表 */
    getReferenceCityListAction () {
      let data = {
        areaCode: this.saleCity.codes
      };
      return new Promise((resolve, reject) => {
        ApiRequest(
          '/sysback/supplyinfofromsrcm/getSupplyCityByAreaCodes',
          'post',
          data,
          true
        )
          .then((res) => {
            if (res.retStatus !== '1') {
              return false;
            }
            let initRetData = res.retData.reduce((value, item) => {
              value.push({
                ...item,
                isSupply: '',
                buyPriceRatio: 1,
                costPriceRatio: 1,
                templateCityName: '',
                templateCityUuid: '',
                saleCityNo: item.cityCode,
                saleCityName: item.cityName,
                saleProvinceNo: item.provinceCode,
                saleProvinceName: item.provinceName,
                templateCitySaleAreaNo: item.areaCode,
                templateCitySaleAreaName: item.areaName
              });
              return value;
            }, []);
            let setCityData = []; // 设置参照城市表格数据
            let supplyReferenceCityList = [];
            initRetData.forEach((item) => {
              setCityData.push({
                ...item,
                supplyUuid: this.supplyInfo.supplierCode,
                _disabled: false
              });
              supplyReferenceCityList.push({
                _disabled: false,
                value: item.saleCityNo,
                label: item.saleCityName
              });
            });
            this.SET_TABLE_DATA(setCityData);
            this.SET_REFERENCE_CITIES(supplyReferenceCityList);
            this.SET_PURCHASE_PRICETYPE(this.supplyPriceType);
            resolve(true);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /* 获取设置完参照城市后的表格数据 */
    handleGetSetData (data) {
      let { tableData, defaultCity } = data;
      if (!tableData) { return false }
      this.defaultReferenceCity = defaultCity || { templateCityUuid: '', templateCityName: '' };
      let uniqTemplateCityData = tableData.reduce((value, item) => {
        /* 区域价格表格数据只取自己参照自己的数据，即销售城市和参照城市相同的数据 */
        if (item.saleCityNo === item.templateCityUuid) {
          value.push({
            buyPriceRatio: item.buyPriceRatio,
            costPriceRatio: item.costPriceRatio,
            isMainSupply: '1',
            isSupply: item.isSupply,
            saleAreaName: item.saleAreaName,
            saleAreaShortNames: item.saleAreaShortNames || null,
            saleAreaUuid: item.saleAreaUuid,
            saleCityName: item.saleCityName,
            saleCityUuid: item.saleCityNo,
            saleProvinceName: item.saleProvinceName,
            saleProvinceUuid: item.saleProvinceNo,
            supplyUuid: item.supplyUuid,
            templateCityUuid: item.templateCityUuid,
            templateCityName: item.templateCityName,
            templateCitySaleAreaName: item.templateCitySaleAreaName,
            templateCitySaleAreaNo: item.templateCitySaleAreaNo
          });
        }
        return value;
      }, []);
      let passedFlag = this.judgeTableNumLimitFn(uniqTemplateCityData);
      if (!passedFlag) { return false }
      this.templateCityData = uniqTemplateCityData;
      if (this.supplyPriceType === '1') {
        this.purchaseTable.unifiedData = this.purchaseTable.initData.reduce((value, item) => {
          value.push({
            ...item,
            supplyUuid: this.supplyInfo.supplierCode,
            templateCityUuid: this.defaultReferenceCity.templateCityUuid
          });
          return value;
        }, []);
      }
      /* 如果是区域进价，需要用表格数据和参照城市数据的乘积重组表格数据 */
      if (this.supplyPriceType === '2') {
        this.reorganizePurchaseTableDataFn();
      }
    },
    /* 设置完参照城市提交调取接口获取重组表格数据 */
    reorganizePurchaseTableDataFn () {
      this.purchaseTable.areaData = this.purchaseTable.initData.reduce(
        (value, item) => {
          this.templateCityData.forEach((val) => {
            value.push({
              ...val,
              ...item
            });
          });
          return value;
        }, []);
    },
    /* 获取submitNo的action请求 */
    getSubmitNoAction (tableData) {
      let dataSource = tableData.reduce((value, item) => {
        value.push({
          buyPriceRatio: item.buyPriceRatio,
          costPriceRatio: item.costPriceRatio,
          isMainSupply: '1',
          isSupply: item.isSupply,
          saleAreaName: item.saleAreaName,
          saleAreaShortNames: item.saleAreaShortNames || null,
          saleAreaUuid: item.saleAreaUuid,
          saleCityName: item.saleCityName,
          saleCityUuid: item.saleCityNo,
          saleProvinceName: item.saleProvinceName,
          saleProvinceUuid: item.saleProvinceNo,
          supplyUuid: item.supplyUuid,
          templateCityUuid: item.templateCityUuid,
          templateCityName: item.templateCityName,
          templateCitySaleAreaName: item.templateCitySaleAreaName,
          templateCitySaleAreaNo: item.templateCitySaleAreaNo
        })
        return value;
      }, [])
      return new Promise((resolve, reject) => {
        ApiRequest(
          `/sysback/supplyarea/batchCreateSupplyAreaCache?supplyUuid=${this.supplyInfo.supplierCode}`,
          'post',
          dataSource
        )
          .then((res) => {
            if (res.retStatus !== '1') {
              resolve(false);
              return false;
            }
            this.submitNo = res.retData;
            resolve(true);
          })
          .catch(() => {
            resolve(false);
          });
      });
    },
    /* 重置参照城市数据 */
    resetReferenceCityDataFn () {
      this.submitNo = '';
      this.templateCityData = [];
      this.DESTORY_STATE();
    },
    /* 关联商品 */
    handleAssociatedGoods () {
      if (!this.supplyInfo.supplierCode) {
        return this.$message.warning('请先选择供应商');
      }
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.associatedGoods.requestApi.url = [
        `/sysback/supplyareaprice/getNoRelSkuList?supplyUuid=${this.supplyInfo.supplierCode}`,
        `/sysback/supplyareaprice/getRelSkuList?supplyUuid=${this.supplyInfo.supplierCode}`
      ];
      this.CHANGE_MODAL_SWITCH(true);
      this.$nextTick(() => {
        this.$refs.link.getDataListAction();
      });
    },
    /* 获取关联商品后的表格数据 */
    getAssociatedGoodsAction () {
      let selectedSkuList = this.getSkuNoListFn(
        this.getListFromMapFn(),
        'productUuid'
      );
      if (selectedSkuList.length === 0) {
        this.purchaseTable.unifiedData = [];
        this.purchaseTable.areaData = [];
        return false;
      }
      let data = {
        productUuids: selectedSkuList.join(',')
      };
      this.resetReferenceCityDataFn(); // 重新关联商品清空参照关系
      this.loading.table = true;
      ApiRequest(
        '/sysback/skuaudit/list/getAuditSkuByProducts',
        'post',
        data,
        true
      )
        .then((res) => {
          this.loading.table = false;
          if (res.retStatus !== '1' || !res.retData) {
            return false;
          }
          /* 初始化数据 */
          this.purchaseTable.initData = res.retData.reduce((value, item) => {
            value.push({
              ...item,
              ...this.taxRateInvoiceInfo,
              freightRatio: 0,
              packRatio: 0,
              processChargesRatio: 0,
              rebateRatio: 0,
              mainUnitCostPrice: 0,
              mainPurchasePrice: 0,
              purchasePrice: 0,
              theoryConvertRatio: 0,
              actualConvertRatio: 0,
              theoryConvertRatioCostPrice: 0,
              actualConvertRatioCostPrice: 0,
              abnormalPurchaseConvertRatio: 0,
              purchasePriceType: this.supplyPriceType
            })
            return value;
          }, [])
          this.switchPurchaseTypeInitTableDataFn(this.purchaseTable.initData);
        })
        .catch(() => {
          this.loading.table = false;
        });
    },
    /* 表格数据更改需要相关字段进行计算 */
    handleRowSpecialChange (data) {
      handleSpecialPriceChangeForMultipleAdd(data, this.supplyPriceType, this.purchaseTable.areaData)
    },
    /* 提交 */
    handleSubmitPurchaseData () {
      if (this.templateCityData.length === 0) {
        return this.$message.warning('请先设置参照城市关系');
      }
      if (
        this.purchaseTable.unifiedData.length > ADD_ENTER_PRICE_INFO_AMOUNT ||
        this.purchaseTable.areaData.length > ADD_ENTER_PRICE_INFO_AMOUNT
      ) {
        return this.$message.warning(
          `当前单据提交的行数不能超过${ADD_ENTER_PRICE_INFO_AMOUNT}`
        );
      }
      let submitList = [];
      if (this.supplyPriceType === '1') {
        submitList = this.purchaseTable.unifiedData.reduce((value, item) => {
          value.push({
            ...item,
            isMainSupply: '1',
            purchasePriceType: this.supplyPriceType,
            supplyUuid: this.supplyInfo.supplierCode,
            templateCityUuid: this.defaultReferenceCity.templateCityUuid
          })
          return value;
        }, []);
      }
      if (this.supplyPriceType === '2') {
        submitList = this.purchaseTable.areaData.reduce((value, item) => {
          value.push({
            ...item,
            isMainSupply: '1',
            purchasePriceType: this.supplyPriceType,
            supplyUuid: this.supplyInfo.supplierCode,
            templateCitySaleAreaNo: item.saleAreaUuid,
            templateCitySaleAreaName: item.saleAreaName,
          })
          return value;
        }, []);
      }
      const { hasEmptyVal, msg } = hasEmptyPriceForMultiple(submitList)
      if (hasEmptyVal) {
        return this.$message.warning(msg);
      }
      this.loading.submit = true;
      ApiRequest(
        `/sysback/supplyareaprice/batchCreateSupplyAreaPrice?batchState=1&randomUuid=${this.submitNo}&chooseAll=${this.saleCity.chooseAll}`,
        'post',
        submitList
      )
        .then((res) => {
          this.loading.submit = false;
          if (res.retStatus !== '1') {
            return false;
          }
          this.$message.success('表格信息提交成功');
          this.$router.push({ name: 'commodityNotPerfection' }); // 跳转待准入页面
        })
        .catch(() => {
          this.loading.submit = false;
        });
    },
    /* 导出 */
    handleExportData () {
      if (!this.supplyInfo.supplierCode) {
        return this.$message.warning('请先选择供应商');
      }
      if (this.templateCityData.length == 0) {
        return this.$message.warning('请先设置参照城市关系');
      }
      let skuNos = this.purchaseTable.initData.map((item) => {
        return item.skuNo;
      });
      let uuid = generateUuid();
      let data = {
        uuid,
        skuNos,
        supplyAreaParams: this.templateCityData,
        productType: 2,
        supplyUuid: this.supplyInfo.supplierCode,
        supplyName: this.supplyInfo.supplierName,
        supplyPriceType: this.supplyPriceType
      };
      this.loading.export = true;
      ApiRequestExportTable(
        '/sysback/supplyareaprice/downLoadTemplateForCreate',
        'post',
        data,
        false
      )
        .then((res) => {
          this.loading.export = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = `批量新增-进价信息多计量模板_${uuid}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.loading.export = false;
          this.$message.error('导出失败');
        });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.loading.table = false;
      this.$message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.loading.table = true;
      if (!this.supplyInfo.supplierCode) {
        return this.$message.warning('请先选择供应商');
      }
      if (this.templateCityData.length === 0) {
        return this.$message.warning('请先设置参照城市关系');
      }
    },
    /* 上传成功 */
    handleUploadSuccess (res) {
      this.loading.table = false;
      let { retData, retStatus, retMessage } = res;
      if (retStatus !== '1') {
        return this.$message.error(retMessage || '导入失败');
      }
      this.$message.success('导入成功');
      retData.forEach(item => {
        const {
          taxRate,
          invoiceType,
          invoiceTypeName
        } = this.taxRateInvoiceInfo
        item.taxRate = taxRate;
        item.invoiceType = invoiceType;
        item.invoiceTypeName = invoiceTypeName;
        this.handleRowSpecialChange({ row: item });
      });
      this.switchPurchaseTypeInitTableDataFn(retData);
    },
    /* 上传失败 */
    handleUploadError () {
      this.loading.table = false;
      this.$message.error('上传失败');
    },
    /* 切换radio时，表格数据的处理操作 */
    switchPurchaseTypeInitTableDataFn (dataSource) {
      if (this.supplyPriceType === '1') {
        this.purchaseTable.unifiedData = _.cloneDeep(dataSource);
        this.purchaseTable.areaData = [];
      }
      if (this.supplyPriceType === '2') {
        this.purchaseTable.areaData = _.cloneDeep(dataSource);
        this.purchaseTable.unifiedData = [];
      }
    },
    /* 校验条数限制 */
    judgeTableNumLimitFn (uniqTemplateCityData) {
      let referenceCityLength = uniqTemplateCityData ? uniqTemplateCityData.length : 0;
      let purchaseTableLength = this.purchaseTable.initData.length || 0;
      let sumLength = referenceCityLength * purchaseTableLength;
      /* 点击设置参照城市按钮时校验表格数据条数 */
      if (!uniqTemplateCityData && purchaseTableLength > ADD_ENTER_PRICE_INFO_AMOUNT) {
        this.$message.warning(
          `当前关联商品行数超过${ADD_ENTER_PRICE_INFO_AMOUNT}行，请重新调整商品后设置`
        )
        return false;
      }
      /* 设置完参照城市后校验表格数据条数 */
      if (
        this.supplyPriceType === '2' &&
        sumLength > ADD_ENTER_PRICE_INFO_AMOUNT
      ) {
        this.$message.warning(
          `参照城市设置完后导致商品行数超过${ADD_ENTER_PRICE_INFO_AMOUNT}行，请重新调整商品后设置`
        );
        return false;
      }
      return true;
    }
  }
};
</script>
<style lang="less" scoped>
.item_wrap {
  margin: 10px 0px;
}
.my_tooltip_wrap {
  min-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
